﻿using System.Collections.ObjectModel;
using System.Diagnostics;

namespace K9Tools.Abstractions.Navigation;

[DebuggerDisplay("{Name}")]
public class NavigationViewItem
{
    public string Name { get; set; }

    public string? Icon { get; set; }

    public string Title { get; set; }

    public string? View { get; set; }

    public int Sort { get; set; }

    public bool Visible { get; set; } = true;

    public ObservableCollection<NavigationViewItem> SubItems { get; } = [];

    public NavigationViewItem()
    {
    }

    public NavigationViewItem(string name, string title, string? icon, string? view = null, int sort = 0)
    {
        Name = name;
        Icon = icon;
        Title = title;
        View = view;
        Sort = sort;
    }

    public NavigationViewItem AddSubItem(NavigationViewItem item)
    {
        item.Name = Name + '.' + item.Name;

        if (item.Sort == 0)
        {
            item.Sort = SubItems.Count;
        }
        else
        {
            for (var i = 0; i < SubItems.Count; i++)
            {
                if (SubItems[i].Sort < item.Sort) continue;

                SubItems.Insert(i, item);
                return this;
            }
        }

        SubItems.Add(item);
        return this;
    }

    public NavigationViewItem RemoveSubItem(NavigationViewItem item)
    {
        SubItems.Remove(item);
        return this;
    }

    public NavigationViewItem CloneWithoutChildren()
    {
        return new NavigationViewItem
        {
            Name = Name,
            Icon = Icon,
            Title = Title,
            View = View,
            Sort = Sort,
        };
    }
}